import cv2 as cv
import numpy as np
img = cv.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\kl.jpg")

# img1 = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# ret,dst= cv.threshold(img1,60,255,cv.THRESH_BINARY)

# 卷积核
# kernel = np.ones((5,5),np.uint8)

# opencvAPI卷积核，MORPH_ELLIPSE椭圆，MORPH_RECT矩形，MORPH_CROSS十字
kernel = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3,3))

# 腐蚀
# erosion = cv.erode(img,kernel,iterations = 1)

# 膨胀
# dilation = cv.dilate(img,kernel,iterations = 1)

# 开运算 先腐蚀再膨胀 去除大图形外的小图形
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
# 闭运算   先膨胀再腐蚀 去除大图形内的小图形
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
# print(erosion)
# print(dilation)

# 梯度运算 原图-腐蚀 求图形边缘
gradient = cv.morphologyEx(img, cv.MORPH_GRADIENT,kernel)

# 顶帽运算 原图-开运算 得到大图形外的小图形
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)

# 黑帽运算 原图-闭运算 得到大图形内的小图形
blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)

cv.imshow("img",img)
cv.imshow("Opening",opening)
cv.imshow("Closing",closing)
cv.imshow("Gradient",gradient)
cv.imshow("Tophat",tophat)
cv.imshow("Blackhat",blackhat)
cv.waitKey(0)